package br.com.converters;

import br.com.modelo.BaseEntity;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "entityConverterBean", forClass = br.com.converters.EntityConverterBean.class)
public class EntityConverterBean implements Converter {

    @Override
    public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
        if (value != null) {
            return this.getAttributesFrom(component).get(value);
        }
        return (BaseEntity) new Object();
    }

    @Override
    public String getAsString(FacesContext ctx, UIComponent component, Object value) {
        BaseEntity entity = (BaseEntity) value;
        Integer id = entity.getId();
        if (value != null && !value.equals("") && id != null) {
            this.addAttribute(component, entity);
            return String.valueOf(id);
        }
        return "";
    }

    protected void addAttribute(UIComponent component, BaseEntity obj) {
        String key = obj.getId().toString();
        this.getAttributesFrom(component).put(key, obj);
    }

    protected Map<String, Object> getAttributesFrom(UIComponent component) {
        return component.getAttributes();
    }
}
